import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rapid_kit/rapid_kit.dart';
import '../../sample/channel/notification.dart';
import '../../sample/configure/constants.dart';
import '../../theme.dart';
import '../../utils/lifecycle_aware.dart';
import '../../utils/persistent_storage.dart';
import '../../utils/platform.dart';
import '../../utils/snack_tips.dart';
import '../../widgets/global_widgets.dart';
import 'home_card.dart';

/// 探鸽demo首页 - 用来调试 - 未启用
/// 启用 - tab_page.dart 42 - 73 注释打开
class HomePagetg extends StatefulWidget {
  const HomePagetg({super.key});

  @override
  State<HomePagetg> createState() => _HomePagetgState();
}

// class _HomePagetgState extends LifecycleAwareState<HomePagetg> {
//
//
//   @override
//   Widget build(BuildContext context) {
//     // TODO: implement build
//     return Text("测试");
//   }
// }

class _HomePagetgState extends LifecycleAwareState<HomePagetg> {
  bool isLoading = true;
  bool isLoadingMore = false;
  final ScrollController _scrollController = ScrollController();
  final List<Primary> _deviceBasicInfoList = [];
  final Map<String, Thumbnail> _thumbnailsMap = {};
  final Map<String, OnlineStatus> _onlineStatusMap = {};
  final Map<String, BatteryStatus> _batteryStatusMap = {};


  @override
  Widget build(BuildContext context) {
    return PlatformUtil.filterPop(
        child: Scaffold(
          body: _safePaddingTop(_buildPageBody(context)),
        ));
  }

  Widget _safePaddingTop(Widget child) {
    return Padding(
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      child: child,
    );
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      isLoading = true;
    });
    _loadData();
    _pushServiceBinding();
    _handleNotificationClick();
  }

  void _handleNotificationClick() async {
    // Notice: we only provide sample on OpenHarmonyOS.
    if (!PlatformUtil.ohos()) {
      return;
    }

    final data = await NotificationChannel.getPendingNotification();

    if (data.isNotEmpty) {
      // You should handle the initial notification data here (launch Notification detail).
      SnackTips.show(context, "Received notification: $data");
    }

    // Then listen to the notification event.
    NotificationChannel.startListening((String data) {
      SnackTips.show(context, "Received notification: $data");
    });
  }

  @override
  void dispose() {
    NotificationChannel.stopListening();
    super.dispose();
  }

  void _pushServiceBinding() async {
    // Notice: we only provide sample on OpenHarmonyOS.
    if (!PlatformUtil.ohos()) {
      return;
    }
    final token = await NotificationChannel.getPushServiceToken();
    final ret = await PushNotificationService.associate(token, PushChannel.harmony);
    if (!ret.success) {
      SnackTips.show(context, "Notice: Push service binding failed");
    }
  }

  void _loadData() async {

    String? savedAccessToken = await SharedPreferencesUtil.instance.getString(SampleConstants.storageKeyLoginToken);
    print("${savedAccessToken}");
    // showToast("==============token===============${savedAccessToken}");
    // LogUtils.e("=======探鸽数据======${savedAccessToken}");
    // json 数据格式
    // Resp{success: true, code: 0, message: null, data: Instance of 'PrimaryByPage'}

    final response = await SpecService.primaryByPage(_deviceBasicInfoList.length);
    List<String> deviceIdList = [];
    // LogUtils.e("=======探鸽数据======${response}");


    if (response.data?.list != null && (response.data?.list?.length ?? 0) > 0) {
      final deviceBasicList = response.data!.list!;
      // LogUtils.e(response.data!.list!);
      for (Primary basic in deviceBasicList) {
        final id = basic.deviceId ?? "";
        deviceIdList.add(id);
      }
    }

    if (deviceIdList.isNotEmpty) {
      final respThumbnail = await SpecService.thumbnailsOfList(deviceIdList);
      if (respThumbnail.success) {
        respThumbnail.data?.forEach((key, value) {
          _thumbnailsMap[key] = value;
        });
      }

      final respOnlineStatus = await SpecService.onlineStatusOfList(deviceIdList);
      if (respOnlineStatus.success) {
        respOnlineStatus.data?.forEach((key, value) {
          _onlineStatusMap[key] = value;
        });
      }

      final respBatteryStatus = await SpecService.batteryStatusOfList(deviceIdList);
      if (respBatteryStatus.success) {
        respBatteryStatus.data?.forEach((key, value) {
          _batteryStatusMap[key] = value;
        });
      }
    }

    if (!mounted) return;

    if (response.success) {
      if ((response.data?.list?.isNotEmpty ?? false) == true) {
        // LogUtils.e(response.data!.list!);

        _deviceBasicInfoList.addAll(response.data!.list!);
      } else {
        if (_deviceBasicInfoList.isNotEmpty) {
          SnackTips.show(context, "没有更多数据了！");
        }
      }
    } else {
      SnackTips.show(context, "请求失败====");
    }

    // Request for notification permission after each data request.
    final enabled = await NotificationChannel.isNotificationEnabled();
    if (!enabled) {
      await NotificationChannel.requestNotificationEnabled();
    }

    setState(() {
      isLoading = false;
      isLoadingMore = false;
    });
  }

  Widget _buildPageBody(BuildContext context) {
    double topPadding = Platform.isMacOS ? 16.0 : 0;
    return Container(
        padding: EdgeInsets.only(left: 16.0, right: 16.0, top: topPadding),
        child: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            // children: <Widget>[
            //   homeTitle(context),
            //   const SizedBox(height: 10),
            //   _buildListContainer(),
            // ],
            children: [
              Text("没有数据"),
              _buildListContainer()
            ],
          ),
        ));
  }

  Widget _buildListContainer() {
    if (!isLoading) {
      final itemCount = _deviceBasicInfoList.length;
      if (itemCount < 1) {
        return _emptyTips();
      }
    }

    return Expanded(
      child: isLoading
          ? createCenterLoading(size: 20.0)
          : RefreshIndicator(
        backgroundColor: SampleThemeConfigure.colorPrimary,
        color: Colors.white,
        displacement: 50,
        onRefresh: _onPullToRefresh,
        child: _buildList(),
      ),
    );
  }

  Expanded _emptyTips() {
    return Expanded(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Icon(Icons.event_note, size: 50, color: SampleThemeConfigure.colorPrimary),
            SizedBox(height: 10),
            Text(
              '名下无设999备',
              style: TextStyle(
                fontSize: 16,
                color: SampleThemeConfigure.colorPrimary,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _onPullToRefresh() async {
    _deviceBasicInfoList.clear();
    setState(() {
      isLoading = true;
    });
    return _loadData();
  }

  // 每一项播放器
  Widget _buildList() {
    return ListView.separated(
      padding: EdgeInsets.zero,
      controller: _scrollController,
      itemCount: _deviceBasicInfoList.length + 1,
      itemBuilder: (context, index) {
        if (index == _deviceBasicInfoList.length) {
          return _buildLoadMore();
        }
        // LogUtils.e("_deviceBasicInfoList[index]${_deviceBasicInfoList[index]}");
        // LogUtils.e("_onlineStatusMap${_onlineStatusMap}");
        // LogUtils.e("_thumbnailsMap${_thumbnailsMap}");
        // LogUtils.e("_batteryStatusMap${_batteryStatusMap}");
        // LogUtils.e("");
        // LogUtils.e("=======探鸽数据======${_deviceBasicInfoList}");
        return homeDeviceCard(_deviceBasicInfoList[index], _onlineStatusMap, _thumbnailsMap, _batteryStatusMap, context, () {
          _onPullToRefresh();
        });
      },
      separatorBuilder: (context, index) => const SizedBox(height: 16.0),
    );
  }

  Widget _buildLoadMore() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, right: 0, bottom: 16),
      child: GestureDetector(
        onTap: () async {
          setState(() {
            isLoadingMore = true;
          });
          _loadData();
        },
        child: Container(
          decoration: BoxDecoration(
            color: SampleThemeConfigure.colorPrimary,
            borderRadius: BorderRadius.circular(8.0),
          ),
          padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 24.0),
          child: Center(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                if (isLoadingMore)
                  const SizedBox(
                    width: 10.0,
                    height: 10.0,
                    child: CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      strokeWidth: 2.0,
                    ),
                  ),
                if (isLoadingMore) const SizedBox(width: 8.0),
                const Text(
                  '点击加载更多',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.0,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget createLoadMore() {
    return SizedBox(
      width: double.infinity,
      height: 50.0,
      child: Center(
        child: createCenterLoading(size: 20.0),
      ),
    );
  }

}
